package com.situ.ftbserver.api;

import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatApi {
    private final ChatClient chatClient;

    @RequestMapping(value = "/chat", produces = "text/html;charset=UTF-8")
    public Flux<String> chat(@RequestParam String question, @RequestParam String userId) {
        System.out.println("question:"+question+" userId:"+userId);
        // 参数校验
        if (question == null || question.trim().isEmpty()) {
            return Flux.just("错误：问题不能为空");
        }

        if (userId == null || userId.trim().isEmpty()) {
            return Flux.just("错误：用户信息未知");
        }

        try {
            // 执行AI聊天逻辑
            return chatClient.prompt()
                    .user(question)
                    .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, userId))
                    .stream()
                    .content();
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            System.err.println("AI聊天处理出错: " + e.getMessage());
            e.printStackTrace();
            return Flux.just("抱歉，AI处理出现问题，请稍后重试。错误信息: " + e.getMessage());
        }
    }


}
